/**
 * Created by xiongisxiong on 2018/5/24
 * 音乐播放界面
 */
import React, { PureComponent } from 'react'
import { View, Text, Image, ImageBackground, StyleSheet, ScrollView, Animated, Easing, TouchableOpacity, TouchableWithoutFeedback } from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import { NavigationActions } from 'react-navigation'
import Slider from 'react-native-slider'

import { screen, color } from '../utils'
import { TextTool, MenuRow, Separator, ModalMenu } from '../widgets' // ModalMenu弹层组件
import { SONG_DETAIL, SONG_LYRIC } from '../api'

import { connect } from 'react-redux'
import { setPlayId, setPlaySong } from '../redux/actions'

const { Normal, Tip, H3 } = TextTool;

class PlayerScene extends PureComponent {
  static navigationOptions = ({navigation}) => ({
    header: <View styl={{width: 0, height: 0}}/>
  });
  constructor(props) {
    super(props)
    this.state = {
      detail: {},
      lyric: '', // 歌词
      lyricArr: [],
      currentLyric: '', // 当前歌词
      showLyric: false,
      lyricScroll: 0, // 初始歌词滚动条位置
      testCurrentPlayId: ''//测试的传进来的音乐id
    };
    this.animatedValue = new Animated.Value(0);
    this.animatedTop = new Animated.Value(0);
  };
  componentDidMount() {
    const { currentPlayId } = this.props;
    console.log('加载后的currentPlayId：', currentPlayId);
    console.log('加载后的this.props：', this.props);
    this.setState({
      testCurrentPlayId: currentPlayId
    })
    this.requestSongDetail(currentPlayId);
    this.requestSongLyric(currentPlayId);
  };
  componentWillReceiveProps(nextProps) {
    // 当props发生变化时执行
    const { currentPlay } = this.props;
    console.log('当props发生变化前执行的currentPlay', currentPlay);
    const nextCurrentPlay = nextProps.currentPlay;
    const { lyric, lyricArr } = this.state;
    console.log('当props发生变化后执行的nextCurrentPlay', nextCurrentPlay);
    if (currentPlay.currentTime !== nextCurrentPlay.currentTime) {
        if (lyric) {    // 匹配当前歌词，并且逐行上滑
            console.log(lyric.match(new RegExp(`\\[${nextCurrentPlay.currentTime}\\.\\d+\\].*`, 'g')));
            const currentLrc = lyric.match(new RegExp(`\\[${nextCurrentPlay.currentTime}\\.\\d+\\].*`, 'g'));
            if (currentLrc) {
                this.setState({currentLyric: currentLrc[0]});
                this.setState({
                    lyricScroll: this.state.lyricScroll += 20,
                }, () => this.lyricScroll && this.lyricScroll.scrollTo({x: 0, y: lyricArr.findIndex(v => v === currentLrc[0]) * 20, animated: true}))
            }
        }
    }
  }
  /* 旋转图片 */
  circling = () => {
    this.animatedValue.setValue(0);
    Animated.timing(this.animatedValue, {
        toValue: 1,
        duration: 12000,
        easing: Easing.linear,
        useNativeDriver: true // 使用原生动画，默认false，在没使用前，旋转会有卡顿，就像是过了1-2秒后才旋转一个度数
    }).start(() => this.circling());
  };
  /* 将top值从start变为end  由于animatedTop只有弹层组件ModalMenu才用到，而ModalMenu组件中重新定义了，所以此处定义无效*/
  // topAnimate = (start = 0, end = 1) => {
  //   this.animatedTop.setValue(start);
  //   Animated.timing(this.animatedTop, {
  //     toValue: end,
  //     duration: 0,
  //     easing: Easing.linear
  //   }).start()
  // }
  /** 返回 */
  goBack = () => {
    // const backAction = NavigationActions.back();
    // navigation.dispatch(backAction);
    // console.log('backAction', backAction)
    this.props.navigation.goBack(); // 与上面两行貌似是一样的效果： 返回
  }
  /** 点击头部右侧的图标时 */
  test = () => {
    this.props.dispatch(setPlayId('186003'))
  }
  requestSongDetail = (id) => {
    try {
      (
        async () => {
          // 详情
          const res = await fetch(SONG_DETAIL + id);
          const detail = (await res.json()).songs[0];
          console.log('详情',detail);
          this.setState({
            detail,
          });
          // 设置setParams动态修改
          this.props.navigation.setParams({
            name:detail.name,
            artists: detail.ar.map(item => item.name).join('、')
          });
          this.circling(); // 旋转图片
        }
      )();
    } catch (err) {
      alert(err)
    } 
  }
  requestSongLyric = (id) => {
    try {
      (
        async () => {
          // 歌词
          const lyRes = await fetch(SONG_LYRIC + id);
          const lyric = (await lyRes.json()).lrc.lyric;
          console.log('歌词',lyric);
          const lyricArr = lyric.split(/\n/);
          this.setState({
            lyric,
            lyricArr
          })
        }
      )();
    } catch (err) {
      alert(err)
    }
  }
  /** 划动条 */
  sliderChange = value => {
    const { currentPlay, dispatch } = this.props;
    dispatch(setPlaySong({sliderProgress: value, ff: currentPlay.duration * value}))
  }
  /** 是否显示歌词 */
  showLyric = () => {
    this.setState({
      showLyric: !this.state.showLyric
    })
  }
  /** 播放歌曲详情--使用了redux全局 */
  playing = playing => {
    this.props.dispatch(setPlaySong({playing}));
  }
  /** 渲染 */
  render() {
    const interpolatedAnimation = this.animatedValue.interpolate({
      inputRange: [0, 1],
      outputRange: ['0deg', '360deg']
    });
    const topAnimation = this.animatedTop.interpolate({
      inputRange: [0, 1],
      outputRange: [screen.height, 0]
    });
    const modalMenus = [
      {leftIcon: 'folder-plus', title: '收藏到歌单'},
      {leftIcon: 'music-note', title: '相似推荐'},
      {leftIcon: 'account', title: '歌手：周杰伦'},
      {leftIcon: 'album', title: '专辑：JAY'},
      {leftIcon: 'link-variant', title: '来源：JAY'},
      {leftIcon: 'music-circle', title: '音质', subTitle: '开通会员畅想更高音质'},
      {leftIcon: 'clock', title: '定时关闭'},
      {leftIcon: 'car', title: '打开驾驶模式'},
    ];
    const { detail, currentLyric, showLyric, lyricArr } = this.state;
    const { params } = this.props.navigation.state;
    const { currentPlay } = this.props;
    return (
      <View style={styles.container}>
        {/* 背后的大背景图片 */}
        <Image style={{width: screen.width, height: screen.height, position: 'absolute', zIndex: 1, opacity: 0.8}} blurRadius={0} source={{uri: detail.al && detail.al.picUrl + '?param=200y200'}}/>
        <View style={{zIndex: 5, flex: 1}}>
            {/* 头部 弹性 左中右 */}
            <View style={styles.headerContainer}>
                <TouchableOpacity onPress={this.goBack}>
                  <Icon name='ios-arrow-back-outline' size={25} color={color.white} />
                </TouchableOpacity>
                <View style={{justifyContent: 'space-between', alignItems: 'center'}}>
                  <Normal color={color.white}>{params.name}</Normal>
                  <Tip color={color.white} style={{fontSize: 9}}>{params.artists}</Tip>
                </View>
                <TouchableOpacity onPress={this.test}>
                  <Icon name='ios-redo-outline' size={25} color={color.white}/>
                </TouchableOpacity>
            </View>
            {/* 主要部分-歌词展示以及唱片圈圈 */}
            <TouchableOpacity style={styles.cdContainer} onPress={this.showLyric}>
                {
                  showLyric ? (
                    <View style={styles.cdContainer}>
                      <ScrollView style={{width: screen.width}} contentContainerStyle={{alignItems: 'center', paddingTop: '30%', paddingBottom: '30%'}} ref={lyricScroll => this.lyricScroll = lyricScroll}>
                        {
                          // 逐条展示歌词，将 '[00:59.83]没有人听懂的傻话' 替换为 '没有人听懂的傻话' 若item是当前显示歌词，则设为主色
                          lyricArr.map((item, index) => (
                          <Normal color={item === currentLyric ? color.theme : color.white} key={index} style={{paddingTop: 5, paddingBottom: 5}}>{item.replace(/\[.*\]/g, '')}</Normal>
                          ))
                        }
                      </ScrollView>
                    </View>
                  ) : (
                    <View style={styles.cdContainer}>
                        <View style={{position: 'absolute', top: 0, left: 34, width: screen.width, alignItems: 'center', zIndex: 18}}>
                            <Image source={require('../imgs/img/needle-ip6.png')} style={{width: 100, height: 140}}/>
                        </View>
                        <ImageBackground source={require('../imgs/img/disc-ip6.png')} style={{width: screen.width - 40, height: screen.width -40, justifyContent: 'center', alignItems: 'center'}}>
                            <Animated.Image 
                                source={{uri: detail.al && detail.al.picUrl + '?param=200y200'}}
                                style={[{width: screen.width - 152, height: screen.width - 152, borderRadius: (screen.width - 152) / 2}, {transform: [{
                                  rotate: interpolatedAnimation
                                }]}]}
                            />
                        </ImageBackground>
                    </View>
                  )
                }
            </TouchableOpacity>
            
            {/* 按钮：收藏、下载、评论、更多 */}
            <View style={styles.topBtn}>
                <TouchableOpacity onPress={() => this.lyricScroll.scrollTo({x: 0, y: 10,animated: true})}>
                    <Icon name='ios-heart-outline' size={25} color={color.white}/>
                </TouchableOpacity>
                <Icon name='ios-cloud-download-outline' size={25} color={color.white}/>
                <Icon name='ios-chatbubbles-outline' size={25} color={color.white}/>
                <TouchableOpacity onPress={() => this.modalMenu.topAnimate(0, 1)}>
                    <Icon name='md-more' size={25} color={color.white} />
                </TouchableOpacity>
            </View>
            {/* 按钮：滑动条 */}
            <View style={styles.sliderBtn}>
                <Tip style={{width: 35}} color={color.white}>{currentPlay.currentTime}</Tip>
                <Slider 
                    maximumTrackTintColor={color.white} //安卓滑块左侧颜色，iOS滑块右侧颜色
                    minimumTrackTintColor={color.theme} //安卓滑块右侧颜色，iOS滑块左侧颜色
                    thumbStyle={styles.thumb}
                    trackStyle={{height: 2}}
                    style={{width: screen.width - 100}}
                    value={currentPlay.sliderProgress}
                    onValueChange={value => this.sliderChange(value)}
                />
                <Tip style={{width: 35}} color='#fff'>{currentPlay.playTime}</Tip>
            </View>
            {/* 底部控制播放按钮 */}
            <View style={styles.footerBtn}>
                <Icon name='ios-repeat-outline' size={30} color={color.white}/>
                <Icon name='ios-skip-backward-outline' size={30} color={color.white}/>
                {
                  currentPlay.playing ? (
                    <TouchableOpacity onPress={() => this.playing(false)}>
                      <Icon name='ios-pause-outline' size={30} color={color.white}/>
                    </TouchableOpacity>
                  ) : (
                    <TouchableOpacity onPress={() => this.playing(true)}>
                      <Icon name='ios-play-outline' size={30} color={color.white}/>
                    </TouchableOpacity>
                  )
                }
                <Icon name='ios-skip-forward-outline' size={30} color={color.white}/>
                <Icon name='ios-list-outline' size={30} color={color.white}/>
            </View>
            {/* 点击更多按钮时的弹层 */}
            <ModalMenu ref={modalMenu => this.modalMenu = modalMenu} style={{paddingBottom: screen.width * 0.137}}>
                <View style={{height: 40, paddingLeft: 8, justifyContent: 'center'}}>
                    <Text style={{fontSize: 12}}>歌曲：测试</Text>
                </View>
                <Separator />
                <ScrollView >
                    {
                      modalMenus.map((item, index) => (
                        <MenuRow key={index} leftIconName={item.leftIcon} title={item.title} subTitle={item.subTitle}/>
                      ))
                    }
                </ScrollView>
            </ModalMenu>
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
      flex: 1,
      backgroundColor: 'transparent'
  },
  headerContainer: {
      height: 50,
      width: screen.width,
      paddingLeft: 15,
      paddingRight: 15,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      borderBottomWidth: screen.onePixel,
      borderColor: 'rgba(245, 245, 245, 0.21)'
  },
  cdContainer: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
  },
  topBtn: {
      height: 30,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-around',
  },
  sliderBtn: {
      height: 40,
      paddingLeft: 10,
      paddingRight: 10,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between'
  },
  thumb: {
      width: 20,
      height: 20,
      backgroundColor: color.theme,
      borderColor: color.white,
      borderWidth: 7,
      borderRadius: 10,
  },
  footerBtn: {
      height: 50,
      width: screen.width,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-around',
  }
});

// 将reducer返回的新state绑定到属性上this.props,即dispatch也绑定到了this.props上，所以第79行就可以获取到dispatch属性
// mapStateToProps是一个函数，{currentPlay} 为reducer中定义好了的currentPlay
const mapStateToProps = ({currentPlay}) => ({
  currentPlayId: currentPlay.id,
  currentPlay
})
export default connect(mapStateToProps)(PlayerScene)